package com.chenxi.vhr.exception;

import com.chenxi.vhr.bean.common.Result;
import com.mysql.jdbc.exceptions.jdbc4.MySQLIntegrityConstraintViolationException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.sql.SQLException;

/**
 * 全局处理异常
 * @author : zhangchenxi
 * @create : 2022-02-04
 **/
@RestControllerAdvice
public class GlobalExceptionHandler  {

    // 捕捉数据库SQL的相关异常
    @ExceptionHandler(SQLException.class)
    public Result sqlException(SQLException ex) {
        // 删除有外键的报错
        if (ex instanceof  MySQLIntegrityConstraintViolationException) {
            Result.error("操作失败，该数据有外键关联的数据！");
        }
        return Result.error("数据库异常，操作失败！");
    }

    @ExceptionHandler(Exception.class)
    public Result exception(Exception ex) {
        return Result.error(ex.getMessage());
    }
}
